﻿using HY.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using HY.Model;
using HY.Service;
using Newtonsoft.Json;

namespace HY.Web.Controllers
{
    public class SysResourceController : BaseController
    {
        public SysResourceController(ILogger<SysResourceController> logger) : base(logger)
        {
            LogModel.TableName = nameof(SysResource);
        }

        [Authorize]
        public IActionResult Index()
        {
            return View();
        }
        [Authorize]
        [HttpPost]
        public IActionResult Index(IFormCollection collection)
        {
            List<SysResource> list = GlobalClass.GetSysResourceList();
            return Json(Success(list.Count, list));
        }

        public IActionResult Add(long id)
        {
            ViewBag.parentId = id;
            return View();
        }
        [HttpPost]
        public IActionResult Add(SysResource model)
        {
            if (!DbContext.SysResource.IsAny(it => it.ResourceUrl == model.ResourceUrl && !string.IsNullOrEmpty(model.ResourceUrl)))
            {
                DbContext.SysResource.Insert(model);
                LogModel.OpeType = "新增";
                LogModel.OpeDetail = JsonConvert.SerializeObject(model);
                LogToDB();
            }
            else
            {
                returnModel.Code = 500;
                returnModel.Message = "Url已存在";
            }
            CacheHelper.Remove(SystemConst.CacheKey.SysResource);
            return Json(returnModel);
        }

        public IActionResult Edit(long id)
        {
            var model = DbContext.SysResource.GetById(id);
            return View(model);
        }

        [HttpPost]
        public IActionResult Edit(SysResource model)
        {
            if (!DbContext.SysResource.IsAny(it => it.Id != model.Id && it.ResourceUrl == model.ResourceUrl && !string.IsNullOrEmpty(model.ResourceUrl)))
            {
                DbContext.db.Updateable(model).IgnoreColumns(it => new { it.AddTime, it.IsDelete }).ExecuteCommand();
                LogModel.OpeType = "修改";
                LogModel.OpeDetail = JsonConvert.SerializeObject(model);
                LogToDB();
            }
            else
            {
                returnModel.Code = 500;
                returnModel.Message = "Url已存在";
            }
            CacheHelper.Remove(SystemConst.CacheKey.SysResource);
            return Json(returnModel);
        }

        [HttpPost]
        public IActionResult Delete(long id)
        {
            DbContext.SysResource.DeleteById(id);
            CacheHelper.Remove(SystemConst.CacheKey.SysResource);
            LogModel.OpeType = "删除";
            LogModel.OpeDetail = $"id={id}";
            LogToDB();
            return Json(returnModel);
        }
    }
}
